<?php


namespace app\crm\controller;

use app\admin\controller\ApiCommon;
use think\Exception;
use think\Hook;
use think\Request;
use think\Db;

class Invoice extends ApiCommon
{
    /**
     * 用于判断权限
     * @permission 无限制
     * @allow 登录用户可访问
     * @other 其他根据系统设置
     **/
    public function _initialize()
    {
        $action = [
            'permission' => [''],
            'allow' => ["get_customer","get_invoice_money"]
        ];
        Hook::listen('check_auth', $action);
        $request = Request::instance();
        $a = strtolower($request->action());
        if (!in_array($a, $action['permission'])) {
            parent::_initialize();
        }
    }

    /**
     * 获取客户列表
     */
    public function get_customer(){
        $param = $this->param;
        $userInfo = $this->userInfo;
        $invoiceModel=model("Invoice");
        $data=$invoiceModel->get_customer($userInfo["id"],$param["customer_name"],$param["order_type"]);
        return resultArray(['data' => $data]);
    }

    /**
     * 获取可开票的金额
     * 先票后款获取合同金额、正常开票获取汇款金额
     */
    public function get_invoice_money(){
        $param = $this->param;
        $userInfo = $this->userInfo;
        $invoiceModel=model("Invoice");
        $data=$invoiceModel->get_invoice_money($param["contract_id"],$param["department"]);
        return resultArray(['data' => $data]);
    }

    /**
     * @param int $money
     * @param string $department
     * @param int $is_butler
     * 获取符合的条件的开票审批
     */
    private function getExamineCategory($invoice_type="",$structure_id){
        $expenceExamine=db("oa_examine_category")
            ->where(["title"=>["like","%开票%"],"status"=>1,"is_deleted"=>0])
            ->field("category_id,structure_ids,invoice_type")->order("money desc")->select();//开票
        if($expenceExamine){
            foreach ($expenceExamine as $k=>$v){
                $structure=$v["structure_ids"]?in_array($structure_id,explode(',',$v["structure_ids"])):"1";
                if(($v["invoice_type"]==$invoice_type || $v["invoice_type"]=="全部") && $structure){
                    return $v["category_id"];
                }
            }
        }
        return "";
    }
    /**
     * 新增一个批量开票单
     */
    public function add(){
        $param = $this->param;
        $userInfo = $this->userInfo;
        Db::startTrans();
        try{
            $categoryId=$this->getExamineCategory($param["order_type"],$userInfo->structure_id);
            if(!$categoryId){
                return resultArray(['error' =>"开票新增失败！没有符合条件的审批！"]);
            }
            //新增审批流程
            $examineStep=DB::name("oa_examine_category")->alias("c")
                ->join("admin_examine_step s","c.flow_id=s.flow_id")
                ->join("admin_examine_flow f","c.flow_id=f.flow_id")
                ->where(["c.category_id"=>$categoryId])->field("f.config,s.flow_id,s.status,s.user_id,s.order_id,s.relation")->order("s.order_id asc")->find();
            if ($examineStep['config'] == 1) {
                //固定审批流
                $examineStepModel = new \app\admin\model\ExamineStep();
                $nextStepData = $examineStepModel->nextStepUser($userInfo['id'], $examineStep['flow_id'], 'oa_examine', 0, 0, 0);
                $check_user_id = $nextStepData['next_user_ids'] ? : '';
                $param['order_id'] = 1;
            } else {
                return resultArray(['error' =>"开票新增失败！没有符合条件的审批！"]);
            }
            //添加审批
            $examineInsertData=[
                "category_id"=>$categoryId,
                "content"=>"{$userInfo["realname"]}开票{$param["invoice_money"]}",
                "remark"=>"开票",
                "money"=>$param["invoice_money"],
                "create_user_id"=>$userInfo["id"],
                "check_user_id"=>is_array($check_user_id) ? ','.implode(',',$check_user_id).',' : $check_user_id,
                "flow_id"=>$examineStep["flow_id"],
                "order_id"=>$examineStep["order_id"],
                "create_time"=>time(),
                "update_time"=>time(),
            ];
            $examineId=Db::name("oa_examine")->insertGetId($examineInsertData);
            //开票信息
            $invoiceInsertData=[
                "department"=>$param["department"],//所属事业部
                "customer_id"=>$param["customer_id"],//开票客户
                "order_type"=>$param["order_type"],//订单类型
                "user_id"=>$userInfo["id"],//开票人
                "invoice_unit"=>$param["invoice_unit"],//开票单位名称（下拉选项：四川轻账财税服务有限公司、纵横云海财税服务(成都)有限公司、成都轻账管家企业管理有限公司、四川轻账科技有限公司）
                "invoice_type"=>$param["invoice_type"],//开票类型(专票、普票)
                "invoice_money"=>$param["invoice_money"],//开票金额
                "service_name"=>$param["service_name"],//货物及应税劳务（下拉选项：纳税申报代理（代账&报税）、一般税务咨询（税优、短期等）、其他经纪代理服务（办件类）、其他税务事项代理（仅代账）、其他咨询服务（财税类不可选））
                "specification_model"=>$param["specification_model"],//规格型号
                "customer_unit"=>$param["customer_unit"],//客户单位名称
                "pay_duty_number"=>$param["pay_duty_number"],//纳税识别号
                "remark"=>$param["remark"],//备注
                "attachment"=>$param["attachment"],//附件
                "created_time"=>date("Y-m-d H:i:s"),
                "updated_time"=>date("Y-m-d H:i:s"),
                "examine_id"=>$examineId,//审批流程id
            ];
            $invoice_id=Db::name("crm_invoice")->insertGetId($invoiceInsertData);
            //开票详情
            $details=$param["detail"];
            $contacts_ids=[];
            $receivables_code_arr=[];
            if($details && is_array($details)){
                foreach ($details as $detail){
                    $contract=Db::name("crm_contract")->where(["contract_id"=>$detail["contract_id"],"crm_upqdbn"=>$param["order_type"],"check_status"=>"2"])->value("contract_id");
                    if(!$contract) throw new Exception("合同id:{$detail['contract_id']}不存在！");
                    if($param["order_type"]=="正常开票" || $detail["order_sn"]){
                        $receivablesInfo=Db::name("crm_finance")->where(["order_type"=>"回款","check_status"=>"2","order_sn"=>$detail["order_sn"]])->value("finance_id");
                        if(!$receivablesInfo) throw new Exception("回款单:{$detail['order_sn']}不存在！");
                    }
                    if(!in_array($detail["contract_id"],$contacts_ids)) $contacts_ids[]=$detail["contract_id"];
                    $invoiceDetailInsertData=[
                        "invoice_id"=>$invoice_id,//
                        "order_sn"=>$detail["order_sn"],//回款编号
                        "contract_id"=>$detail["contract_id"],//客户名称
                        "contract_type"=>$param["order_type"],//订单类型
                        "total_money"=>$detail["total_money"],//合同或者回款总金额
                        "used_money"=>$detail["used_money"],//已开票金额
                        "money"=>$detail["money"],//开票金额
                    ];
                    $receivables_code_arr[]=$detail["order_sn"];
                    Db::name("crm_invoice_detail")->insert($invoiceDetailInsertData);
                }
            }
            //更新
            Db::name("crm_invoice")->where(["id"=>$invoice_id])->update(["order_sn_all"=>implode(",",$receivables_code_arr)]);
            //审批关联数据
            $examineRelationInsertData=[
                "examine_id"=>$examineId,
                "contract_ids"=>",".implode(",",$contacts_ids).",",
                "create_time"=>time(),
            ];
            Db::name("oa_examine_relation")->insert($examineRelationInsertData);
            Db::commit();
            return resultArray(['data' => '开票新增成功！']);
        }catch (Exception $e){
            Db::rollback();
            return resultArray(['error' =>$e->getMessage()]);
        }
    }
    /**
     * 修改批量开票
     */
    public function update(){
        $param = $this->param;
        $invoice=Db::name("crm_invoice")->where(["id"=>$param["id"],"status"=>["in",array("0","3","4")]])->find();//只允许审批拒绝和撤回的开票单修改
        if(!$invoice) return resultArray(['error' => "该开票单不存在或者不可修改！"]);
        $userInfo = $this->userInfo;
        Db::startTrans();
        try{
            //开票信息
            $invoiceUpdateData=[
                "department"=>$param["department"],//所属事业部
                "customer_id"=>$param["customer_id"],//开票客户
                "order_type"=>$param["order_type"],//订单类型
                "user_id"=>$userInfo["id"],//开票人
                "invoice_unit"=>$param["invoice_unit"],//开票单位名称（下拉选项：四川轻账财税服务有限公司、纵横云海财税服务(成都)有限公司、成都轻账管家企业管理有限公司、四川轻账科技有限公司）
                "invoice_type"=>$param["invoice_type"],//开票类型(专票、普票)
                "invoice_money"=>$param["invoice_money"],//开票金额
                "service_name"=>$param["service_name"],//货物及应税劳务（下拉选项：纳税申报代理（代账&报税）、一般税务咨询（税优、短期等）、其他经纪代理服务（办件类）、其他税务事项代理（仅代账）、其他咨询服务（财税类不可选））
                "specification_model"=>$param["specification_model"],//规格型号
                "customer_unit"=>$param["customer_unit"],//客户单位名称
                "pay_duty_number"=>$param["pay_duty_number"],//纳税识别号
                "remark"=>$param["remark"],//备注
                "attachment"=>$param["attachment"],//附件
                "updated_time"=>date("Y-m-d H:i:s"),
                "status"      => 0
            ];
            Db::name("crm_invoice")->where(["id"=>$invoice["id"]])->update($invoiceUpdateData);
            //修改审批流程
            $examineStep=DB::name("oa_examine")->alias("c")
                ->join("admin_examine_step s","c.flow_id=s.flow_id")
                ->join("admin_examine_flow f","c.flow_id=f.flow_id")
                ->where(["c.examine_id"=>$invoice["examine_id"]])->field("f.config,s.flow_id,s.status,s.user_id,s.order_id,s.relation")->order("s.order_id asc")->find();
            if ($examineStep['config'] == 1) {
                //固定审批流
                $examineStepModel = new \app\admin\model\ExamineStep();
                $nextStepData = $examineStepModel->nextStepUser($userInfo['id'], $examineStep['flow_id'], 'oa_examine', 0, 0, 0);
                $check_user_id = $nextStepData['next_user_ids'] ? : '';
            } else {
                return resultArray(['error' =>"开票修改失败！没有符合条件的审批！"]);
            }
            Db::name("oa_examine")->where(["examine_id"=>$invoice["examine_id"]])->update(["money"=>$param["invoice_money"],"content"=>"{$userInfo["realname"]}开票{$param["invoice_money"]}","check_status"=>0,"order_id"=>1,"check_user_id"=>','.implode(',',$check_user_id).',',"flow_user_id"=>""]);
            //删除原有的审批记录
            Db::name("admin_examine_record")->where(["types"=>"oa_examine","types_id"=>$invoice["examine_id"],"flow_id"=>$examineStep['flow_id']])->delete();
            //开票详情
            $details=$param["detail"];
            $contacts_ids=[];
            $receivables_code_arr=[];
            if($details && is_array($details)){
                foreach ($details as $detail){
                    $contract=Db::name("crm_contract")->where(["contract_id"=>$detail["contract_id"],"crm_upqdbn"=>$param["order_type"],"check_status"=>"2"])->value("contract_id");
                    if(!$contract) throw new Exception("合同id:{$detail['contract_id']}不存在！");
                    if($param["order_type"]=="正常开票" || $detail["order_sn"]){
                        $receivablesInfo=Db::name("crm_finance")->where(["order_type"=>"回款","check_status"=>"2","order_sn"=>$detail["order_sn"]])->value("finance_id");
                        if(!$receivablesInfo) throw new Exception("回款单:{$detail['order_sn']}不存在！");
                    }
                    if(!in_array($detail["contract_id"],$contacts_ids)) $contacts_ids[]=$detail["contract_id"];
                    $invoiceDetailInsertData=[
                        "invoice_id"=>$invoice["id"],//
                        "order_sn"=>$detail["order_sn"],//回款编号
                        "contract_id"=>$detail["contract_id"],//客户名称
                        "contract_type"=>$param["order_type"],//订单类型
                        "total_money"=>$detail["total_money"],//合同或者回款总金额
                        "used_money"=>$detail["used_money"],//已开票金额
                        "money"=>$detail["money"],//开票金额
                        "status"=>0,
                    ];
                    if($param["order_type"]=="正常开票"){
                        $invoiceDetailId=Db::name("crm_invoice_detail")->where(["order_sn"=>$detail["order_sn"],"invoice_id"=>$invoice["id"]])->value("id");
                    }else{
                        $invoiceDetailId=Db::name("crm_invoice_detail")->where(["contract_id"=>$detail["contract_id"],"invoice_id"=>$invoice["id"]])->value("id");
                    }
                    if($invoiceDetailId){
                        $receivables_code_arr[]=$detail["order_sn"];
                        Db::name("crm_invoice_detail")->where(["id"=>$invoiceDetailId])->update($invoiceDetailInsertData);
                    }else{
                        Db::name("crm_invoice_detail")->insert($invoiceDetailInsertData);
                    }
                }
                //清楚本次删除的数据
                Db::name("crm_invoice_detail")->where(["order_sn"=>array("not in",$receivables_code_arr),"invoice_id"=>$invoice["id"]])->delete();
                //更新
                Db::name("crm_invoice")->where(["id"=>$invoice["id"]])->update(["order_sn_all"=>implode(",",$receivables_code_arr)]);
                //审批关联数据
                $examineRelationInsertData=[
                    "examine_id"=>$invoice['examine_id'],
                    "contract_ids"=>",".implode(",",$contacts_ids).",",
                    "create_time"=>time(),
                ];
                Db::name("oa_examine_relation")->where(["examine_id"=>$invoice['examine_id']])->update($examineRelationInsertData);
            }
            Db::commit();
            return resultArray(['data' => '批量开票修改成功！']);
        }catch (Exception $e){
            Db::rollback();
            return resultArray(['error' =>$e->getMessage()]);
        }
    }
    /**
     * 获取开票详情
     */
    public function detail(){
        $param = $this->param;
        $invoice=Db::name("crm_invoice")->where(["id"=>$param["id"]])->find();
        if($invoice){
            $invoice["customer_name"]=Db::name("crm_customer")->where(["customer_id"=>$invoice["customer_id"]])->value("name");//客户名称
            $invoice["user_name"]=Db::name("admin_user")->where(["id"=>$invoice["user_id"]])->value("realname");//报销人
            $invoiceDetails=Db::name("crm_invoice_detail")->where(["invoice_id"=>$invoice["id"]])->select();
            if($invoiceDetails){
               foreach ($invoiceDetails as $k=>$v){
                   $invoiceDetails[$k]["contract_num"]=Db::name("crm_contract")->where(["contract_id"=>$v["contract_id"]])->value("num");
               }
            }
            $invoice["detail"]=$invoiceDetails;
            //审批记录
            $invoice["examineRecord"]=Db::name("admin_examine_record")->alias("r")
                ->join("admin_user admin","admin.id=r.check_user_id","left")
                ->where(["r.types"=>"oa_examine","r.types_id"=>$invoice["examine_id"]])
                ->order("r.record_id asc")
                ->field("admin.realname,r.status,FROM_UNIXTIME(r.check_time,'%Y-%m-%d %H:%i') as check_time,r.content")
                ->select();
        }
        return resultArray(['data' => $invoice]);
    }

    /**
     * 开票列表
     * */
    public function index()
    {
        $PersonnelModel = model('Invoice');
        $param = $this->param;
        $userInfo = $this->userInfo;
        $param['user_id'] = $userInfo['id'];
        $data = $PersonnelModel->getDataList($param);
        return resultArray(['data' => $data]);
    }

}
